package com.expdatacloud.service.impl;

import com.expdatacloud.entity.*;
import com.expdatacloud.mapper.*;
import com.expdatacloud.service.IqcCheckItemDetailsService;
import com.expdatacloud.service.IqcDetectionDetailService;
import com.expdatacloud.service.IqcDetectionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * IQC-检测表 服务实现类
 * </p>
 *
 * @author jie
 * @since 2019-11-13
 */
@Service
@Transactional
public class IqcDetectionServiceImpl implements IqcDetectionService {

    @Autowired
    private IqcDetectionMapper iqcDetectionMapper;
    @Autowired
    private IqcSamplingShowMapper iqcSamplingShowMapper;
    @Autowired
    private IqcCheckItemDetailsMapper iqcCheckItemDetailsMapper;
    @Autowired
    private IqcCheckItemDetailsService iqcCheckItemDetailsService;
    @Autowired
    private IqcDetectionDetailService iqcDetectionDetailService;
    @Autowired
    private IqcDetectionHistoryMapper iqcDetectionHistoryMapper;

    @Override
    public List<IqcDetection> list(IqcDetection iqcDetection) {
        if (iqcDetection.getInspectionCategoryDesc() != null && !"".equals(iqcDetection.getInspectionCategoryDesc())) {
            String inspectionCategory = iqcDetectionMapper.getCode(iqcDetection.getInspectionCategoryDesc());
            if (inspectionCategory != null && !"".equals(inspectionCategory)) {
                iqcDetection.setInspectionCategory(inspectionCategory);
            }
        }
        List<IqcDetection> iqcDetectionList = iqcDetectionMapper.list(iqcDetection);

        for (IqcDetection detection : iqcDetectionList) {
            if (detection.getInspectionCategory() != null && !"".equals(detection.getInspectionCategory())) {
                String inspectionCategoryDesc = iqcDetectionMapper.getDescription(detection.getInspectionCategory());
                detection.setInspectionCategoryDesc(inspectionCategoryDesc);
            }
        }
        return iqcDetectionList;
    }


    @Override
    public IqcDetection getByReceiptkeyAndSku(IqcDetection iqcDetection) {
        if (iqcDetectionMapper.list(iqcDetection) == null) {
            return null;
        }
        IqcDetection iqcDetection1 = iqcDetectionMapper.list(iqcDetection).get(0);
        iqcDetection1.setDecideWayList(iqcDetectionMapper.getDecideWay("NO"));
        return iqcDetection1;
    }

    @Override
    public int submit(IqcDetection iqcDetection, String user,
                      String checkItemName, String library) {

        //如果已经生成履历则不允许保存或提交
        IqcDetection iqcDetection1 = iqcDetectionMapper.getBySkuAndReceiptKey(iqcDetection.getSku(), iqcDetection.getReceiptKey());

        // 如果判定方式是特采,则校验特采单号和上传文件
        if ("2".equals(iqcDetection.getDecideWay())) {
            if (iqcDetection.getSpecialMiningOrder() == null || "".equals(iqcDetection.getSpecialMiningOrder().trim())) {
                throw new RuntimeException("判定方式为特采,特采单号不可为空!");
            }

            if (iqcDetection.getFileName() == null || "".equals(iqcDetection.getFileName().trim())) {
                throw new RuntimeException("判定方式为特采,请先上传附件!");
            }
        }

        // 如果为拒收,则入库数量必须等于0
        if ("1".equals(iqcDetection.getDecideWay())) {
            if (iqcDetection.getRejectionQuantity() <= 0) {  //rejectionQuantity
                throw new RuntimeException("判定方式为拒收,拒收数量必须大于0!");
            }
        }

        if (StringUtils.isNotEmpty(iqcDetection1.getToHistory())) {
            throw new RuntimeException("已经生成履历则不允许保存或提交");
        }

        if ("合格".equals(iqcDetection.getCheckResult())) {
            iqcDetection.setDecideWay("0");
        }

        // 如果入库数量大于0不允许是拒收
        if (iqcDetection.getInventoryQuantity() > 0 && "1".equals(iqcDetection.getDecideWay())) {
            throw new RuntimeException("入库数量大于0,不允许判定方式为拒收");
        }
        //检验项目
        List<IqcCheckItemDetails> checkItemList = iqcCheckItemDetailsService.list(checkItemName, iqcDetection.getReceiptKey(), iqcDetection.getSku());
        //检验明细  receiptKey:receiptKey,sku:sku
        IqcDetectionDetail iqcDetectionDetail = new IqcDetectionDetail();
        iqcDetectionDetail.setReceiptKey(iqcDetection.getReceiptKey());
        iqcDetectionDetail.setSku(iqcDetection.getSku());
        List<IqcDetectionDetail> iqcDetectionDetailList = iqcDetectionDetailService.list(iqcDetectionDetail);
        iqcDetection.setQualityStatus("3");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        iqcDetection.setReceiveTime(simpleDateFormat.format(new Date()));
        //如果判定为拒收的话修改对应的数量
        if ("1".equals(iqcDetection.getDecideWay())) {
            //提交的时候修改明细表的数据 拒收货数量、验退数量直接取待检数量
            iqcDetectionDetailService.cleanData(iqcDetectionDetail, user, "拒收");
        }
        //写入数据到履历的三张表
        int toHistory = iqcCheckItemDetailsService.writeDateToHistory(user, library, iqcDetection, checkItemList, iqcDetectionDetailList);

        //调用移库存储 和内部转移存储
        String result = iqcCheckItemDetailsService.pro_yt_3nod_move(iqcDetectionDetailList, user, iqcDetection);

        iqcDetection.setEditWho(user);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        iqcDetection.setEditDate(dateFormat.format(new Date()));
        iqcDetection.setToHistory("1");
        iqcDetection.setCheckItemFlag("Y");
        return iqcDetectionMapper.update(iqcDetection);
    }

    @Override
    public int submitCheckItem(IqcDetection iqcDetection, String user,String library,String checkItemName) {
        String sku = iqcDetection.getSku();
        String receiptKey = iqcDetection.getReceiptKey();

        if (StringUtils.isBlank(sku) && StringUtils.isBlank(receiptKey)) {
            throw new RuntimeException("参数不能为空");
        }

        if (StringUtils.isBlank(iqcDetection.getCheckResult())) {
            throw new RuntimeException("检验结果不能为空");
        }

        if (StringUtils.isBlank(iqcDetection.getModelKey())) {
            throw new RuntimeException("机型不能为空");
        }

        if (StringUtils.isBlank(iqcDetection.getCulprit())) {
            throw new RuntimeException("由于检测结果不合格，不良原因必填");
        }

        if ("合格".equals(iqcDetection.getCheckResult())) {
            iqcDetection.setDecideWay("0");
        }

        // 如果入库数量大于0不允许是拒收
        if (iqcDetection.getInventoryQuantity() > 0 && "1".equals(iqcDetection.getDecideWay())) {
            throw new RuntimeException("入库数量大于0,不允许判定方式为拒收");
        }


        updateIqcDetection(iqcDetection, user);

        //新增检验项目履历
        List<IqcCheckItemDetails> checkItemList = iqcCheckItemDetailsService.list(checkItemName, iqcDetection.getReceiptKey(), iqcDetection.getSku());
        iqcCheckItemDetailsService.insertToHistory(user,library,iqcDetection,checkItemList);

        // 修改履历表检验结果、判定方式
        iqcDetectionHistoryMapper.updateHistory(iqcDetection);
        return 1;
    }

    /**
     * 更新主表的状态
     */
    private void updateIqcDetection(IqcDetection iqcDetection, String user) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        iqcDetection.setEditWho(user);
        iqcDetection.setEditDate(dateFormat.format(new Date()));
        iqcDetection.setCheckItemFlag("Y");
        iqcDetectionMapper.update(iqcDetection);
    }

    @Override
    public int update(IqcDetection iqcDetection, String user) {

        //如果已经生成履历则不允许保存或提交
        IqcDetection iqcDetection1 = iqcDetectionMapper.getBySkuAndReceiptKey(iqcDetection.getSku(), iqcDetection.getReceiptKey());

        if (StringUtils.isNotEmpty(iqcDetection1.getToHistory())) {
            throw new RuntimeException("已经生成履历则不允许保存或提交");
        }

        if ("合格".equals(iqcDetection.getCheckResult())) {
            iqcDetection.setDecideWay("0");
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        iqcDetection.setEditWho(user);
        iqcDetection.setEditDate(dateFormat.format(new Date()));

        IqcDetectionDetail iqcDetectionDetail = new IqcDetectionDetail();
        iqcDetectionDetail.setReceiptKey(iqcDetection.getReceiptKey());
        iqcDetectionDetail.setSku(iqcDetection.getSku());

//        List<IqcDetectionDetail> iqcDetectionDetailList = iqcDetectionDetailService.list(iqcDetectionDetail);
        //如果判定为拒收的话修改对应的数量
        if ("1".equals(iqcDetection.getDecideWay())) {
            //提交的时候修改明细表的数据 拒收货数量、验退数量直接取待检数量
            iqcDetectionDetailService.cleanData(iqcDetectionDetail, user, "拒收");
        }
        return iqcDetectionMapper.update(iqcDetection);
    }

    /**
     * 获取检验结果
     */
    @Override
    public String getResult(String receiptKey, String sku) {
        //致命缺陷
        double criticalDefectNumber = 0;
        //严重缺陷
        double seriousDefectsNumber = 0;
        //轻微缺陷
        double lightDefectsNumber = 0;
        //获取aql表的数据
        List<IqcSamplingShow> iqcSamplingShowServiceList = iqcSamplingShowMapper.list(receiptKey, sku);
        for (IqcSamplingShow iqcSamplingShow : iqcSamplingShowServiceList) {
            if ("致命缺陷".equals(iqcSamplingShow.getDefectLevels())) {
                criticalDefectNumber = iqcSamplingShow.getRejectionNumber();
            }
            if ("严重缺陷".equals(iqcSamplingShow.getDefectLevels())) {
                seriousDefectsNumber = iqcSamplingShow.getRejectionNumber();
            }
            if ("轻微缺陷".equals(iqcSamplingShow.getDefectLevels())) {
                lightDefectsNumber = iqcSamplingShow.getRejectionNumber();
            }
        }

        //检验结果
        String result = "合格";
        //遍历检验项目表 判断 值为NG的 获取 他们的不良数
        List<IqcCheckItemDetails> checkItemList = iqcCheckItemDetailsMapper.list(null, receiptKey, sku);
        int criticalDefectSum = 0;
        int seriousDefectsSum = 0;
        int lightDefectsSum = 0;

        for (IqcCheckItemDetails checkItemDetails : checkItemList) {
            if (null != checkItemDetails.getCriticalDefect() && "NG".equalsIgnoreCase(checkItemDetails.getCriticalDefect().trim())) {
                criticalDefectSum += checkItemDetails.getNumberOfDefectiveSa();
                if (criticalDefectSum >= criticalDefectNumber) {
                    result = "不合格";
                    break;
                }
            } else if (null != checkItemDetails.getSeriousDefects() && "NG".equalsIgnoreCase(checkItemDetails.getSeriousDefects().trim())) {
                seriousDefectsSum += checkItemDetails.getNumberOfDefectiveSa();
                if (seriousDefectsSum >= seriousDefectsNumber) {
                    result = "不合格";
                    break;
                }
            } else if (null != checkItemDetails.getLightDefects() && "NG".equalsIgnoreCase(checkItemDetails.getLightDefects().trim())) {
                lightDefectsSum += checkItemDetails.getNumberOfDefectiveSa();
                if (lightDefectsSum >= lightDefectsNumber) {
                    result = "不合格";
                    break;
                }
            }
        }
        return result;
    }
}
